package com.itheima.Controller;

import com.itheima.Service.ProductService;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Product;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RequestMapping("/api/products")
@Slf4j
@RestController
public class ProductController {
    @Autowired
    private ProductService productService;

    /*
     *   分页查询所有商品
     *   使用@RequestParam来设置默认值
     *   原始写法
     *   新写法：可以使用pagehelper插件
     * */
    @GetMapping
    private Result page(@RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer pageSize,
                        String name, Integer category_id,
                        @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                        @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
        log.info("分页查询所有商品,参数:{},{},{},{},{},{}", page, pageSize, name, category_id, begin, end);
        PageBean pageBean = productService.page(page, pageSize, name, category_id, begin, end);
        return Result.success(pageBean);
    }

    /*
     *   批量删除商品
     * */
    @DeleteMapping("/{ids}")
    private Result delete(@PathVariable List<Integer> ids) {
        log.info("调用删除商品接口,{}", ids);
        productService.deleteProductById(ids);
        return Result.success();
    }

    /*
     *   新增商品
     * */
    @PostMapping()
    private Result add(@RequestBody Product product) {
        log.info("调用新增接口,{}", product);
        productService.addProduct(product);
        return Result.success();
    }

    /*
     *   根据id获取修改商品信息
     * */
    @GetMapping("/{id}")
    private Result get(@PathVariable int id) {
        log.info("调用查询商品接口,id:{}", id);
        Product product = productService.getProduct(id);
        return Result.success(product);
    }

    /*
     *   更新商品信息
     * */
    @PutMapping
    private Result update(@RequestBody Product product) {
        log.info("调用更新商品接口,需要修改的数据:{}", product);
        productService.updateProduct(product);
        return Result.success();
    }

    /*
     *   校验农产品的名称是否存在
     * */
    @GetMapping("/validate/{name}")
    private Result validate(@PathVariable String name) {
        log.info("调用校验农产品名称接口,{}", name);
        Product product = productService.validate(name);
        if (product != null) return Result.success("已有该农场品名称");
        return Result.success();
    }
}
